package com.mbigger.admin.service.impl;

import com.google.common.base.Joiner;
import com.mbigger.admin.beans.CacheKeyConstants;
import com.mbigger.admin.service.CacheService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CacheServiceImpl implements CacheService{

	@Autowired
	private static StringRedisTemplate stringRedisTemplate;

	private void setIfPresent(String key, String value, int ttl) {
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(value)) {
			return;
		}
		stringRedisTemplate.opsForValue().setIfPresent(key, value, ttl, TimeUnit.SECONDS);
	}

	public void set(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
		if (toSavedValue == null) {
			return;
		}
		try {
			String cacheKey = generateCacheKey(prefix, keys);
			setIfPresent(cacheKey, toSavedValue, timeoutSeconds);
		} catch (Exception e) {
			log.error("set cache exception, prefix:{}, keys:{}", prefix.name(), String.join(",", keys));
			log.error("set cache exception, {}", e);
		}
	}

	public String get(CacheKeyConstants prefix, String... keys) {
		String cacheKey = generateCacheKey(prefix, keys);
		try {
			String value = get(cacheKey);
			return value;
		} catch (Exception e) {
			log.error("get cache exception, prefix:{}, keys:{}", prefix.name(), String.join(",", keys));
			log.error("get cache exception, {}", e);
			return null;
		}
	}
	
	private String get(String key) {
		if (StringUtils.isEmpty(key)) {
			return null;
		}

		return stringRedisTemplate.opsForValue().get(key);
	}

	private String generateCacheKey(CacheKeyConstants prefix, String... keys) {
		String key = prefix.name();
		if (keys != null && keys.length > 0) {
			key += "_" + Joiner.on("_").join(keys);
		}
		return key;
	}

}
